﻿<%@ WebHandler Language="C#" Class="getSMSCode" %>

using System;
using System.Web;
using System.Web.SessionState;
using Models;
using Newtonsoft.Json;


public class getSMSCode : IHttpHandler, IRequiresSessionState
{
    Entities db = new Entities();

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        var phone=HttpContext.Current.Request.Form["phoneNum"];
        // string phone = context.Request.QueryString["phoneNum"];
        // string checkCode = context.Request.QueryString["checkcode"];
        string code = "", msg = "", verificationCode = "" ;

        if (string.IsNullOrEmpty(phone))
        {
            code = "1";
            msg = "手机号不能为空！";
            context.Response.Write(JsonConvert.SerializeObject(new { code, msg }));
        }
        else
        {
            string _msg = "";
            string smscode = "",CheckCode="";
            //try
            //{
            //    CheckCode = HttpContext.Current.Session["SmsCheckCode"].ToString();
            //}
            //catch
            //{
            //    CheckCode = "";
            //}

            if (context.Session["time"] != null)
            {
                string time = context.Session["time"].ToString();
                DateTime d = DateTime.Now;
                DateTime.TryParse(time, out d);
                if (d.AddSeconds(60) > DateTime.Now)
                {
                    code = "2";
                    msg = string.Format("短信请求过于频繁，请于{0}秒后再试！", (int)(d.AddSeconds(60) - DateTime.Now).TotalSeconds);
                    context.Response.Write(JsonConvert.SerializeObject(new { code, msg }));
                }
            }
            SmsTool smsT = new SmsTool();

            bool success = smsT.SendSmsCode(phone, "您的验证码是{0},请您10分钟以内使用。", out _msg, out smscode);
            if (success)
            {
                code = "0";
                msg = "发送验证码成功！";
                context.Session["smscode"] = smscode;
                context.Session["forphone"] = phone;
                context.Session["time"] = DateTime.Now.ToString();
                verificationCode = smscode;
            }
            else
            {
                code = "1";
                msg = "发送验证短信失败！-" + _msg;

            }
            context.Response.Write(JsonConvert.SerializeObject(new { code, msg,verificationCode }));

        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}